﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;


namespace sales.Controls
{
    //Incomplete
    public class gridOrderDetail : common.controls.baseDataGridView 
    {
        public gridOrderDetail()
        {
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.AutoArrange();
            this.myOnFind += new OnCellEvent(FindData);
        }

        public enum ColumnNames
        {
            deleted, itemCode, itemName, unit, qty, whQty, price, fPrice,
            taxPercent, taxAmount, taxFAmount, amount, fAmount, reduceAmt, reduceFAmt, notes, tag1, actionBtn
        };

        public void UpdateItemList()
        {
            UpdateItemList(null);
        }
        public void UpdateItemList(string itemCode)
        {
            if (itemCode == null)
            {
                for (int idx = 0; idx < this.Rows.Count; idx++)
                {
                    if (this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value == null) continue;
                    DataAccess.DataCache.FindITEM(this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value.ToString());
                }
            }
            else DataAccess.DataCache.FindITEM(itemCode);
        }
        public override void Init(BindingSource dataSource)
        {
            base.Init(dataSource);

            data.salesDS.OrderDetailDataTable detailTbl = (data.salesDS.OrderDetailDataTable)dataSource.DataSource;
            DataGridViewCellStyle taxPercCellStyle = new DataGridViewCellStyle();
            DataGridViewCellStyle amountCellStyle = new DataGridViewCellStyle();
            DataGridViewCellStyle famountCellStyle = new DataGridViewCellStyle();
            DataGridViewCellStyle qtyCellStyle = new DataGridViewCellStyle();

            taxPercCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            taxPercCellStyle.Format = "N" + common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskPercentTax).ToString(); amountCellStyle.NullValue = null;

            amountCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            amountCellStyle.Format = "N" + common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskLocalAmt).ToString(); amountCellStyle.NullValue = null;

            famountCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            famountCellStyle.Format = "N" + common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskForeignAmt).ToString();
            famountCellStyle.NullValue = null;

            qtyCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            qtyCellStyle.Format = "N" + common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskQtySales).ToString(); qtyCellStyle.NullValue = null;

            //delete
            DataGridViewCheckBoxColumn deleted = new DataGridViewCheckBoxColumn();
            deleted.DataPropertyName = detailTbl.deletedColumn.ColumnName;
            deleted.Name = ColumnNames.deleted.ToString();
            deleted.Width = 20;
            deleted.HeaderText = "";
            deleted.Visible = false;

            // 
            // itemCode
            // 
            common.controls.DataGridViewTextBoxColumnExt itemCode = new common.controls.DataGridViewTextBoxColumnExt();
            itemCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemCode.Uppercase = true;
            itemCode.HeaderText = "Mã.hàng";
            itemCode.Name = ColumnNames.itemCode.ToString();
            itemCode.Width = 100;
            itemCode.Uppercase = true;

            // 
            // itemName
            // 
            BindingSource itemSource = new BindingSource();
            itemSource.DataSource = DataAccess.DataCache.myMasterDS.Item;

            DataGridViewComboBoxColumn itemName = new DataGridViewComboBoxColumn();
            itemName.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemName.DataSource = itemSource;
            itemName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.nameColumn.ColumnName;
            itemName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.HeaderText = "Diễn giải";
            itemName.Name = ColumnNames.itemName.ToString();
            itemName.ReadOnly = true;
            itemName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            itemName.Width = 200;
            itemName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            itemName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;
            // 
            // unit
            // 
            DataGridViewComboBoxColumn unit = new DataGridViewComboBoxColumn();
            unit.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            unit.DataSource = itemSource;
            unit.DisplayMember = DataAccess.DataCache.myMasterDS.Item.unitColumn.ColumnName;
            unit.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.HeaderText = "ĐVT";
            unit.Name = ColumnNames.unit.ToString();
            unit.ReadOnly = true;
            unit.ValueMember = "itemCode";
            unit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            unit.Width = 50;
            unit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            unit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;

            // 
            // Qty
            // 
            DataGridViewTextBoxColumn qty = new DataGridViewTextBoxColumn();
            qty.DataPropertyName = detailTbl.qtyColumn.ColumnName;
            qty.DefaultCellStyle = qtyCellStyle;
            qty.HeaderText = "Lượng";
            qty.Name = ColumnNames.qty.ToString();
            qty.Width = 70;

            // 
            // whQty
            // 
            DataGridViewTextBoxColumn whQty = new DataGridViewTextBoxColumn();
            whQty.DefaultCellStyle = qtyCellStyle;
            whQty.HeaderText = "SL.Kho";
            whQty.Name = ColumnNames.whQty.ToString();
            whQty.Width = 70;
            whQty.Visible = false;
            whQty.ReadOnly = true;

            // 
            // Price
            // 
            DataGridViewTextBoxColumn price = new DataGridViewTextBoxColumn();
            price.DataPropertyName = detailTbl.priceColumn.ColumnName;
            price.DefaultCellStyle = amountCellStyle;
            price.HeaderText = "  Giá";
            price.Name = ColumnNames.price.ToString();
            price.Width = 100;

            // 
            // Price
            // 
            DataGridViewTextBoxColumn fPrice = new DataGridViewTextBoxColumn();
            fPrice.DataPropertyName = detailTbl.fPriceColumn.ColumnName;
            fPrice.DefaultCellStyle = famountCellStyle;
            fPrice.HeaderText = "Giá.NT";
            fPrice.Name = ColumnNames.fPrice.ToString();
            fPrice.Width = 80;
            fPrice.Visible = false;

            // 
            // Amount
            // 
            DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
            amount.DataPropertyName = detailTbl.amountColumn.ColumnName;
            amount.DefaultCellStyle = amountCellStyle;
            amount.HeaderText = "Thành tiền";
            amount.Name = ColumnNames.amount.ToString();
            amount.Width = 120;
            // 
            // fAmount
            // 
            DataGridViewTextBoxColumn fAmount = new DataGridViewTextBoxColumn();
            fAmount.DataPropertyName = detailTbl.fAmountColumn.ColumnName;
            fAmount.DefaultCellStyle = famountCellStyle;
            fAmount.HeaderText = "Ngoại tệ";
            fAmount.Name = ColumnNames.fAmount.ToString();
            fAmount.Width = 100;
            fAmount.Visible = false;

            // 
            // taxPercent
            // 
            DataGridViewTextBoxColumn taxPercent = new DataGridViewTextBoxColumn();
            taxPercent.DataPropertyName = detailTbl.taxPercentColumn.ColumnName;
            taxPercent.DefaultCellStyle = taxPercCellStyle;
            taxPercent.HeaderText = "%";
            taxPercent.Name = ColumnNames.taxPercent.ToString();
            taxPercent.Width = 25;
            taxPercent.Visible = false;

            // 
            // taxAmount
            // 
            DataGridViewTextBoxColumn taxAmount = new DataGridViewTextBoxColumn();
            taxAmount.DataPropertyName = detailTbl.taxAmtColumn.ColumnName;
            taxAmount.DefaultCellStyle = amountCellStyle;
            taxAmount.HeaderText = " Thuế";
            taxAmount.Name = ColumnNames.taxAmount.ToString();
            taxAmount.Width = 90;
            taxAmount.Visible = false;

            // 
            // taxFAmount
            // 
            DataGridViewTextBoxColumn taxFAmount = new DataGridViewTextBoxColumn();
            taxFAmount.DataPropertyName = detailTbl.taxFAmtColumn.ColumnName;
            taxFAmount.DefaultCellStyle = famountCellStyle;
            taxFAmount.HeaderText = " Thuế";
            taxFAmount.Name = ColumnNames.taxFAmount.ToString();
            taxFAmount.Width = 70;
            taxFAmount.Visible = false;
            // 
            // Reduce Amount
            // 
            DataGridViewTextBoxColumn reduceAmt = new DataGridViewTextBoxColumn();
            reduceAmt.DataPropertyName = detailTbl.reduceAmtColumn.ColumnName;
            reduceAmt.DefaultCellStyle = amountCellStyle;
            reduceAmt.HeaderText = "Giảm.trừ";
            reduceAmt.Name = ColumnNames.reduceAmt.ToString();
            reduceAmt.Width = 80;
            reduceAmt.Visible = false;
            // 
            // Reduce fAmount
            // 
            DataGridViewTextBoxColumn reduceFAmt = new DataGridViewTextBoxColumn();
            reduceFAmt.DataPropertyName = detailTbl.reduceFAmtColumn.ColumnName;
            reduceFAmt.DefaultCellStyle = famountCellStyle;
            reduceFAmt.HeaderText = "Giảm.trừ";
            reduceFAmt.Name = ColumnNames.reduceFAmt.ToString();
            reduceFAmt.Width = 80;
            reduceFAmt.Visible = false;
            // 
            // Notes
            // 
            DataGridViewTextBoxColumn notes = new DataGridViewTextBoxColumn();
            notes.DataPropertyName = detailTbl.notesColumn.ColumnName;
            notes.HeaderText = "Ghi chú";
            notes.Name = ColumnNames.notes.ToString();
            notes.Width = 100;
            notes.Visible = false;

            // 
            // actionBtn
            // 
            common.controls.gridViewImageColumn actionBtn = new common.controls.gridViewImageColumn();
            actionBtn.Name = ColumnNames.actionBtn.ToString();
            actionBtn.Width = 25;
            actionBtn.HeaderText = "";
            actionBtn.Visible = true;
            actionBtn.myImageType = common.controls.imageType.Edit;


            fAmount.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorHiLightBG1;
            fAmount.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorHiLightFG1;

            reduceFAmt.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorHiLightBG1;
            reduceFAmt.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorHiLightFG1;

            taxFAmount.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorHiLightBG1;
            taxFAmount.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorHiLightFG1;

            fPrice.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorHiLightBG1;
            fPrice.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorHiLightFG1;

            this.DataSource = dataSource;
            this.AutoGenerateColumns = false;
            this.Columns.Clear();
            this.Columns.AddRange(new DataGridViewColumn[] {
                    deleted,itemCode,itemName,qty,whQty, unit,fPrice,price,fAmount,amount,reduceFAmt,reduceAmt,
                    taxPercent,taxFAmount,taxAmount,notes, actionBtn});
            this.ScrollBars = ScrollBars.Vertical;

            this.myAutoFitColumn = itemName.Name;
            this.DisbaleReadOnlyColumns();
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
        }
        protected override void OnDefaultValuesNeeded(DataGridViewRowEventArgs e)
        {
            base.OnDefaultValuesNeeded(e);
            if (e == null) return;
            if (myDataSource.Current != null)
                DataAccess.DataLibs.InitData((data.salesDS.OrderDetailRow)((DataRowView)myDataSource.Current).Row);
        }
        
        public override void Refresh()
        {
            if (IsOnProcessing) return;
            try
            {
                IsOnProcessing = true;
                UpdateItemList(null);
                IsOnProcessing = false;
                base.Refresh();
            }
            catch (Exception er)
            {
                IsOnProcessing = false;
                ErrorHandler(this, er);
            }
        }

        public override bool CheckData()
        {
            this.myDataSource.EndEdit();
            return DoValidateData(OnRowValidate);
        }
        private void OnRowValidate(DataGridViewRow row, common.controls.GridRowValidateEventArgs e)
        {
            if (row.DataBoundItem == null) return;

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible)
            {
                if (row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() == "")
                {
                    e.ErrorText.Add(String.Format("Dữ liệu [{0}] trống", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                    e.HaveError = true;
                }
            }
            //=========================
            //Check data contrainsts
            //=========================

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible &&
                row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() != "" &&
                DataAccess.DataCache.FindITEM(row.Cells[ColumnNames.itemCode.ToString()].Value.ToString()) == null)
            {
                e.ErrorText.Add(String.Format("Dữ liệu [{0}] không hợp lệ", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                e.HaveError = true;
            }
        }
        
        private void FindData(object sender, common.controls.GridEventArgs arg)
        {
            string findCode = this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].EditedFormattedValue.ToString(); ;
            if (this.CurrentCell == null) return;
            //Code
            if (this.Columns[arg.ColumnIndex].Name.Trim() == ColumnNames.itemCode.ToString())
            {
                application.dataFind.myItemFind.Find(findCode, true);
                data.masterDS.ItemRow itemRow = application.dataFind.myItemFind.selectedDataRow;
                if (itemRow != null)
                {
                    this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = itemRow.itemCode;
                    UpdateItemList(itemRow.itemCode);
                }
                else this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = DBNull.Value;
                this.myDataSource.ResetCurrentItem();
                this.myDataSource.EndEdit(); 
            }
        }
    }
}
